import React, { useState } from 'react';
import { Button, Checkbox, Form, Input, message } from 'antd';
import type { FormProps, CheckboxProps } from 'antd';
import { CheckboxChangeEvent } from 'antd/es/checkbox';
import { userLogin } from '@/store/modules/userStore';
import { useDispatch } from 'react-redux';
import './LoginForm.scss';
import { useNavigate } from 'react-router-dom';
import { ResponseType } from '@/type/ResponseType';

export type FieldType = {
  mobile: string;
  password: string;
};

const mobileRules = [
  { required: true, message: '请输入手机号' },
];

const passwordRules = [
  { required: true, message: '请输入密码' },
];

const LoginForm: React.FunctionComponent = () => {
  const dispatch = useDispatch();
  const navigate = useNavigate();
  const [checked, setChecked] = useState<boolean>(true);
  /**
   * @description 表单提交事件
   * */
  const onFinish: FormProps<FieldType>['onFinish'] = async (formData: FieldType) => {
    if (!checked) return message.warning('请勾选平台协议');
    try {
      const loginResponse: ResponseType<string> = await dispatch(userLogin(formData)).unwrap();
      navigate('/');
      message.success(loginResponse.message);
    } catch (rejectedValueOrSerializedError: any) {
      message.error(rejectedValueOrSerializedError);
    }
  };
  /**
   * @description 复选框勾选事件
   * */
  const onChange: CheckboxProps['onChange'] = (eevet: CheckboxChangeEvent) => {
    setChecked(eevet.target.checked);
  };
  return (
    <div className="login-form">
      <h1>黑马人力资管理系统</h1>
      <Form validateTrigger="onBlur" onFinish={onFinish}>
        <Form.Item<FieldType> name="mobile" rules={mobileRules}>
          <Input placeholder="请输入手机号" size="large"></Input>
        </Form.Item>
        <Form.Item<FieldType> name="password" rules={passwordRules}>
          <Input type="password" placeholder="请输入密码" size="large"></Input>
        </Form.Item>
        <Form.Item>
          <Checkbox className="checked" checked={checked} onChange={onChange}>用户平台使用协议</Checkbox>
        </Form.Item>
        <Form.Item>
          <Button type="primary" size="large" htmlType="submit">登录</Button>
        </Form.Item>
        <p className="tip">仅用于IT培训教学使用，为保障您的个人信息安全，请勿向平台录入任何个人敏感信息 (如手机号、身份证号等)!</p>
        <span className="tip">手机号:13800000002</span> <span className="tip">密码:hm#qd@23!</span>
      </Form>
    </div>
  );
};

export default LoginForm;
